package com.quan.weixin.api.oauth;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.quan.common.bean.R;
import com.quan.common.core.MyBaseController;
import com.quan.weixin.commons.vo.WxUserVo;
import com.quan.weixin.entity.WeixinOauthUser;
import com.quan.weixin.service.WeixinOauthUserService;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;

/**
 * 微信小程序登录
 * 
 * @author yhaoquan
 *
 */
@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("/api/wx/ma")
public class WxMaOAuthController extends MyBaseController {

	@Autowired
	private WxMaService wxMaService;

	@Autowired
	private WeixinOauthUserService weixinOauthUserService;

	/**
	 * wx.login()获取code，通过code获取openid
	 * 
	 * @param code
	 * @param vo
	 * @return
	 */
	@PostMapping(value = "/oauth/{code}")
	public Object authorize(@PathVariable String code, @RequestBody WxUserVo vo) {
		log.debug("==>微信小程序登录");

		try {
			if (StringUtils.isEmpty(code)) {
				return R.failure("无效的code");
			} else {
				WxMaJscode2SessionResult session = this.wxMaService.getUserService().getSessionInfo(code);
				vo.setOpenid(session.getOpenid());
				vo.setSessionKey(session.getSessionKey());
				vo.setUnionid(session.getUnionid());

				// 根据OPENID查询数据
				WeixinOauthUser weixinUser = this.weixinOauthUserService.findByOpenId(vo.getOpenid());

				if (null == weixinUser) { // 用户不存在
					// 将授权用户存储到数据库
					WeixinOauthUser user = new WeixinOauthUser();
					user.setOpenid(vo.getOpenid());
					user.setHeadimgurl(vo.getHeadimgurl());
					user.setNickname(vo.getNickname());
					this.weixinOauthUserService.save(user);
				}

				log.info("==> 登录信息: {}", vo);
				return R.ok(vo);
			}
		} catch (WxErrorException e) {
			e.printStackTrace();
		}
		return R.failure();
	}

	/**
	 * <pre>
	 * 获取用户信息接口
	 * </pre>
	 */
	@GetMapping("/info")
	public Object info(@PathVariable String appid, String sessionKey, String signature, String rawData, String encryptedData, String iv) {
		// 用户信息校验
		if (!this.wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
			return "user check failed";
		}
		// 解密用户信息
		WxMaUserInfo userInfo = this.wxMaService.getUserService().getUserInfo(sessionKey, encryptedData, iv);

		return R.ok(userInfo);
	}

	/**
	 * <pre>
	 * 获取用户绑定手机号信息
	 * </pre>
	 */
	@GetMapping("/phone")
	public Object phone(@PathVariable String appid, String sessionKey, String signature, String rawData,
			String encryptedData, String iv) {

		// 用户信息校验
		if (!this.wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
			return "user check failed";
		}

		// 解密
		WxMaPhoneNumberInfo phoneNoInfo = this.wxMaService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
		return R.ok(phoneNoInfo);
	}

}
